<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserlist">
            <el-button @click="getUserlist" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 用户列表区 -->
    <el-table :data="userList" border stripe>
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column label="姓名" prop="username"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="电话" prop="mobile"></el-table-column>
      <el-table-column label="角色" prop="role_name"></el-table-column>
      <el-table-column label="状态">
        <!-- 作用域插槽 -->
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template  slot-scope="scope">
          <!-- 修改按钮 -->
          <el-button @click="showEditDialog(scope.row.id)" type="primary" icon="el-icon-edit" size="mini"></el-button>
          <!-- 删除按钮 -->
          <el-button @click="removeUserById(scope.row.id)" type="danger" icon="el-icon-delete" size="mini"></el-button>
          <!-- 分配角色按钮 -->
          <el-tooltip effect="dark" content="分配角色" placement="top-start">
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 3, 4, 5]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      >
    </el-pagination>
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
    <!-- 内容主体区 -->
      <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addFrom.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addFrom.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
      >
        <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="editFrom.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisable"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {},
  data () {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[A-Za-z0-9]+([_\][A-Za-z0-9]+)*@([A-Za-z0-9-]+\.)+[A-Za-z]{2,6}$/
      if (regEmail.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    var checkPhone = (rule, value, cb) => {
      const regPhone = /^1[3456789]\d{9}$/
      if (regPhone.test(value)) {
        // 合法的手机号码
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表的参数列表
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      userList: [],
      total: 0,
      // 控制对话框的显示与隐藏
      dialogVisible: false,
      // 添加用户的数据对象
      addFrom: {
        username: '',
        password: '',
        email: '',
        phone: ''
      },
      // 添加用户验证信息的对象
      addFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码的长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 修改框的显示与消失
      editDialogVisible: false,
      // 查询到的用户信息对象
      editFrom: {},
      // 修改表单的验证规则对象
      editFromRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 控制分配角色的对话框的显示与隐藏
      setRoleDialogVisable: false,
      // 需要分配权限的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      selectedRoleId: ''
    }
  },
  methods: {
    async getUserlist () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize改变的事件
    handleSizeChange (v) {
      this.queryInfo.pagesize = v
      this.getUserlist()
    },
    handleCurrentChange (p) {
      console.log(p)
      this.queryInfo.pagenum = p
      this.getUserlist()
    },
    // 监听switch开关的状态
    async userStateChange (v) {
      console.log(v)
      const { data: res } = await this.$http.put(`users/${v.id}/state/${v.mg_state}`)
      if (res.meta.status !== 200) {
        v.mg_state = !v.mg_state
        return this.$message.error('用户状态更新失败')
      }
      this.$message.success('用户状态成功')
    },
    // 监听对话框关闭事件
    addDialogClosed () {
      // 清空表单
      this.$refs.addFromRef.resetFields()
    },
    // 点击按钮添加用户
    addUser () {
      this.$refs.addFromRef.validate(async valid => {
        console.log(valid)
        if (!valid) return false
        // 发起网络请求
        const { data: res } = await this.$http.post('users', this.addFrom)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败!')
        this.$message.success('添加用户成功!')
        // 隐藏用户列表
        this.dialogVisible = false
        this.getUserlist()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询用户信息失败!')
      this.editFrom = res.data
      this.editDialogVisible = true
      console.log(res.data)
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed () {
      console.log(this.$refs.editFromRef)
      this.$refs.editFromRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo () {
      this.$refs.editFromRef.validate(async v => {
        if (!v) return false
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$http.put(`users/${this.editFrom.id}`, {
          email: this.editFrom.email,
          mobile: this.editFrom.mobile
        })
        if (res.meta.status !== 200) {
          this.$message.error('更新用户信息失败！')
        }
        // 关闭对话框
        this.editDialogVisible = false
        this.getUserlist()
        this.$message.success('修改用户信息成功！')
      })
    },
    // 根据id删除用户信息
    async removeUserById (id) {
      // 弹框询问用户是否修改数据
      const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 用户确认删除返回confirm
      // 用户取消删除返回字符串cansel
      if (res !== 'confirm') return this.$message.info('您已经取消了删除操作')
      // 发起请求删除用户
      const { data: removeres } = await this.$http.delete(`users/${id}`)
      console.log(removeres)
      if (removeres.meta.status !== 200) return this.$message.error(removeres.meta.msg)
      this.$message.success(removeres.meta.msg)
      this.getUserlist()
    },
    // 展示分配角色的对话框
    async setRole (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败！')
      this.rolesList = res.data
      this.setRoleDialogVisable = true
    },
    // 点击按钮，分配角色
    async saveRolesInfo () {
      if (!this.selectedRoleId) return this.$message.error('请选择要分配用户的角色！')
      console.log(this.selectedRoleId)
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('分配用户角色失败！')
      this.$message.success('分配用户角色成功！')
      this.getUserlist()
      this.setRoleDialogVisable = false
    },
    // 监听对话框的关闭事件，清空下拉菜单
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  },
  components: {},
  created () {
    this.getUserlist()
  }
}
</script>

<style scoped lang="scss">
</style>
